library(cjoint); library(estimatr)

load("conjoint_data.RData")

# Define a list of attributes of the conjoint (the nominee attributes)
attribute_list <- list()
attribute_list[["Rhetoric"]] <- c("No","Yes")
attribute_list[["Age"]] <- c("45","55","65")
attribute_list[["Gender"]] <- c("Male","Female")
attribute_list[["Race"]] <- c("White", "Black","Hispanic or Latino/a")
attribute_list[["Law School"]] <- c("Elite/Ivy", "Well-regarded public","Second-tier regional","Not top 100")
attribute_list[["Current Position"]] <-c("Federal judge","Elected politician","Law professor","Think-tank","Corporate defense attorney")
attribute_list[["Abortion View"]] <-c("Roe is settled law","Cannot comment","Roe should be overturned")

attribute.names.full <- c("Rhetoric","Age","Gender","Race","Law School","Current Position","Abortion View")

# Create the conjointDesign object
datadesign <- makeDesign(type="constraints",attribute.levels=attribute_list)

# Change the attribute names that will be displayed in the model output
levels.test.full<-list()
levels.test.full[["var1"]]<-c("No","Yes")
levels.test.full[["var2"]]<-c("45","55","65")
levels.test.full[["var3"]]<-c("Male","Female")
levels.test.full[["var4"]]<-c("White","Black","Hispanic or Latino/a") 
levels.test.full[["var5"]]<-c("Elite Ivy","Well-regarded public","Second tier","Non-top 100")
levels.test.full[["var6"]]<-c("Federal Judge","Elected politician","Law professor","Chief counsel","Corporate attorney")
levels.test.full[["var7"]]<-c("Roe settled law","Cannot comment","Overturn Roe")

#######################################
# Figure 1.a: Support for the nominee #
#######################################
# Subset dataset to respondents who answered the support question  
data.support <- data[!(is.na(data$support) | data$support==""), ]

# Define variables to pass into model
data.support$var1 <- factor(data.support$politicized) # Whether respondent recieved elite rhetoric
data.support$var2 <- factor(data.support$treat_age) # Age
data.support$var3 <- factor(data.support$treat_gender) # Gender
data.support$var4 <- factor(data.support$treat_race) # Race
data.support$var5 <- factor(data.support$treat_lawS) # Law school
data.support$var6 <- factor(data.support$treat_currentP) # Current position
data.support$var7 <- factor(data.support$treat_pAbortion) # Abortion view
data.support$Politicized <- data.support$var1 # Whether respondent recieved elite rhetoric
data.support$Party <- as.factor(data.support$pid3a) # Respondent partisanship

# Estimate the AMCEs, cluster SEs by respondent
results.support <- amce(support ~ var1*Party + var2*Party + var3*Party +  var4*Party + var5*Party + var6*Party + var7*Party, 
                        data=data.support, cluster=TRUE, respondent.varying="Party", respondent.id="caseid", weights="weight")

# Create Figure 1.a
f1a.support <- plot(results.support, facet.names = "Party", plot.display="interaction", attribute.names = attribute.names.full,
                    label.baseline=F, level.names=levels.test.full, main = "", xlab="Estimated effect", xlim=c(-1.25,1.25),
                    color="black")

##################################################
# Figure 1.b: Perceptions of judicial legitimacy #
##################################################
# Subset dataset to respondents who answered the legitimacy questions 
data.legitimacy <- data[!(is.na(data$legit.additive)), ]

# Define variables to pass into model
data.legitimacy$var1 <- factor(data.legitimacy$politicized)
data.legitimacy$var2 <- factor(data.legitimacy$treat_age)
data.legitimacy$var3 <- factor(data.legitimacy$treat_gender)
data.legitimacy$var4 <- factor(data.legitimacy$treat_race)
data.legitimacy$var5 <- factor(data.legitimacy$treat_lawS)
data.legitimacy$var6 <- factor(data.legitimacy$treat_currentP)
data.legitimacy$var7 <- factor(data.legitimacy$treat_pAbortion)
data.legitimacy$Politicized <- data.legitimacy$var1 # Whether respondent recieved elite rhetoric
data.legitimacy$Party <- as.factor(data.legitimacy$pid3a)

# Estimate the AMCEs, cluster SEs by respondent
results.legitimacy <- amce(legit.additive ~ var1*Party + var2*Party + var3*Party + var4*Party + var5*Party + var6*Party 
                           + var7*Party, data=data.legitimacy, cluster=TRUE, respondent.varying="Party", 
                           respondent.id="caseid", weights="weight")

# Create Figure 1.b
f1b.legitimacy <- plot(results.legitimacy,facet.names = "Party",plot.display="interaction", 
                       attribute.names = attribute.names.full, label.baseline=F, level.names=levels.test.full, main = "", 
                       xlab="Estimated effect", xlim=c(-.35,.35), color="black")

#######################################################
# Figure 2.a: Polarization of support for the nominee #
#######################################################
# Linear regression of support on indicator for the rhetoric condition interacted with partisanship
f2.a.reg <- lm(support ~ Politicized * Party, data=data.support, weights=weight)
# Calculating standard errors from model clustered on respondent 
f2.a.reg.robust <- commarobust(f2.a.reg, clusters=data.support$caseid, se_type = "stata")
# Calculating predicted values from model
f2.a.dataset <- data.frame(Politicized=as.factor(c(0,1,0,1)), Party=c("Democrat","Democrat","Republican","Republican"))
f2.a.fitted.robust <- predict(f2.a.reg.robust, f2.a.dataset, type=c("response"), se.fit=T)

# Creating the plot
coef <- c(f2.a.fitted.robust$fit[1],f2.a.fitted.robust$fit[3],f2.a.fitted.robust$fit[2],f2.a.fitted.robust$fit[4])
se <- c(f2.a.fitted.robust$se.fit[1],f2.a.fitted.robust$se.fit[3],f2.a.fitted.robust$se.fit[2],f2.a.fitted.robust$se.fit[4])
lb <- coef-1.96*se
ub <- coef+1.96*se
pid <- c(1.02,.90,0,0)
var <- c("No rhetoric","No rhetoric","Rhetoric","Rhetoric")
party <- c("D","R","D","R")

results <- data.frame(coef,se,lb,ub,pid,var,party)
results$var <- reorder(results$var,rep(1:2,each=2))

col <- c("GREY","BLACK","GREY","BLACK")
pd <- position_dodge(width=0.01)

ggplot(results, aes(coef,pid,color=col,alpha=.5)) +
  geom_point(aes(shape=party),size=4) + 
  scale_color_manual(values=c("grey40","black")) + 
  scale_shape_manual(values=c(19,18)) +
  scale_x_continuous("Predicted support", limits=c(2.4,3.35),breaks=c(2.5,2.75,3,3.25),labels=c("2.5","2.75","3","3.25")) + 
  scale_y_continuous("",limits=c(-.25,1.25),breaks=c(0,1),labels=c("Rhetoric   ","No rhetoric")) +
  geom_segment(aes(x = lb, y = pid, xend = ub, yend = pid, linetype=c("1","1","1","1")),position=pd, lwd=1.5) +
  theme_bw(base_size = 12) +
  theme(panel.grid.minor = element_blank()) +
  theme(panel.grid.major = element_blank()) +
  theme(axis.ticks.x=element_blank()) +
  theme(axis.ticks.y=element_blank()) +
  theme(legend.position = "none")  +
  theme(axis.text.x=element_text(size=11)) +
  theme(axis.text.y=element_text(size=12)) +
  theme(legend.title=element_blank()) +
  theme(legend.key = element_blank()) +
  annotate("text", x = 3, y = 1.1, label = "Difference  = 0.08 (p = .307)") +
  annotate("text", x = 2.9, y = .1, label = "Difference  = 0.68 (p < .001)") +
  annotate("text", x = 2.55, y = -.05, label = "Dem.") +
  annotate("text", x = 3.23, y = -.05, label = "Rep.") +
  annotate("text", x = 2.96, y = .97, label = "Dem.") +
  annotate("text", x = 3.04, y = .85, label = "Rep.")

##################################################################
# Figure 2.b: Polarization of perceptions of judicial legitimacy #
##################################################################
# Linear regression of legitimacy evaluations on indicator for the rhetoric condition interacted with partisanship
f2.b.legitimacy.reg <- lm(legit.additive ~ Politicized * Party, data=data.legitimacy, weights=weight)
# Calculating standard errors from model clustered on respondent 
f2.b.legitimacy.reg.robust <- commarobust(f2.b.legitimacy.reg, clusters=data.legitimacy$caseid, se_type = "stata")
# Calculating predicted values from model
f2.b.dataset <- data.frame(Politicized=as.factor(c(0,1,0,1)), Party=c("Democrat","Democrat","Republican","Republican"))
f2.b.legitimacy.fitted.robust <- predict(f2.b.legitimacy.reg.robust, f2.b.dataset, type=c("response"), se.fit=T)

# Creating the plot
coef <- c(f2.b.legitimacy.fitted.robust$fit[1],f2.b.legitimacy.fitted.robust$fit[3],f2.b.legitimacy.fitted.robust$fit[2],f2.b.legitimacy.fitted.robust$fit[4])
se <- c(f2.b.legitimacy.fitted.robust$se.fit[1],f2.b.legitimacy.fitted.robust$se.fit[3],f2.b.legitimacy.fitted.robust$se.fit[2],f2.b.legitimacy.fitted.robust$se.fit[4])
lb <- coef-1.96*se
ub <- coef+1.96*se
pid <- c(1.02,.90,0,0)
var <- c("No rhetoric","No rhetoric","Rhetoric","Rhetoric")
party <- c("D","R","D","R")

results <- data.frame(coef,se,lb,ub,pid,var,party)
results$var <- reorder(results$var,rep(1:2,each=2))

col <- c("GREY","BLACK","GREY","BLACK")
pd <- position_dodge(width=0.01)

ggplot(results, aes(coef,pid,color=col,alpha=.5)) +
  geom_point(aes(shape=party),size=4) + 
  scale_color_manual(values=c("grey40","black")) + 
  scale_shape_manual(values=c(19,18)) + 
  scale_x_continuous("Predicted legitimacy", limits=c(2.8,3.4),breaks=c(2.8,3,3.2,3.4),labels=c("2.8","3","3.2","3.4")) + 
  scale_y_continuous("",limits=c(-.25,1.25),breaks=c(0,1),labels=c("Rhetoric   ","No rhetoric")) +
  geom_segment(aes(x = lb, y = pid, xend = ub, yend = pid, linetype=c("1","1","1","1")),position=pd, lwd=1.5) +
  theme_bw(base_size = 12) +
  theme(panel.grid.minor = element_blank()) +
  theme(panel.grid.major = element_blank()) +
  theme(axis.ticks.x=element_blank()) +
  theme(axis.ticks.y=element_blank()) +
  theme(legend.position = "none")  +
  theme(axis.text.x=element_text(size=11)) +
  theme(axis.text.y=element_text(size=12)) +
  theme(legend.title=element_blank()) +
  theme(legend.key = element_blank()) +
  annotate("text", x = 3.1, y = 1.1, label = "Difference  = 0.03 (p = .667)") +
  annotate("text", x = 3.1, y = .1, label = "Difference  = 0.31 (p < .001)") +
  annotate("text", x = 2.94, y = -.05, label = "Dem.") +
  annotate("text", x = 3.26, y = -.05, label = "Rep.") +
  annotate("text", x = 3.13, y = .97, label = "Dem.") +
  annotate("text", x = 3.16, y = .85, label = "Rep.")

#########################################
# Figure 3: Perceptions of impartiality #
#########################################
# Subset dataset to respondents who answered the trust in nominee impartiality question  
data.impartiality <- data[!(is.na(data$trust)), ]

# Define variables to pass into model
data.impartiality$var1 <- factor(data.impartiality$politicized)
data.impartiality$var2 <- factor(data.impartiality$treat_age)
data.impartiality$var3 <- factor(data.impartiality$treat_gender)
data.impartiality$var4 <- factor(data.impartiality$treat_race)
data.impartiality$var5 <- factor(data.impartiality$treat_lawS)
data.impartiality$var6 <- factor(data.impartiality$treat_currentP)
data.impartiality$var7 <- factor(data.impartiality$treat_pAbortion)
data.impartiality$Politicized <- data.impartiality$var1 # Whether respondent recieved elite rhetoric
data.impartiality$Party <- as.factor(data.impartiality$pid3a)

# Estimate the AMCEs, cluster SEs by respondent
results.impartiality <- amce(trust ~ var1*Party + var2*Party + var3*Party + var4*Party + var5*Party + var6*Party + var7*Party, 
                             data=data.impartiality, cluster=TRUE, respondent.varying="Party", respondent.id="caseid", 
                             weights="weight")

# Create Figure 3
f3.impartiality <- plot(results.impartiality, label.baseline=F, facet.names = "Party",plot.display="interaction", 
                        attribute.names = attribute.names.full, level.names=levels.test.full, main="", 
                        xlab="Estimated effect", xlim=c(-1,.75), color="black")
